<template>
  <div class="upload-part">
    <template v-if="dataSrc">
      <a v-if="dataSrc.includes('.doc')" title="点击下载预览" :href="dataSrc"><img
          src="@/assets/img/icon-word.png" alt=""></a>

      <a v-else-if="dataSrc.includes('.pdf')" title="点击预览" @click="viewPdf"><img
          src="@/assets/img/icon-pdf.png" alt=""></a>

      <img v-else class="view-img" :src="dataSrc" alt="">
    </template>

    <div>
      <el-button @click="upload">上传附件</el-button>
      <div class="tips-txt"> {{ $t('global.typeWarn',{0: '.jpg|.png|.pdf|.doc'})}}</div>
    </div>

  </div>
</template>

<script>
  import {
    uploadFile
  } from '@/utils/uploadFile'
  export default {
    data() {
      return {
        dataSrc: ''
      }
    },
    props: ['dataPath'],
    watch: {
        dataPath(nVal,oVal){
           this.dataSrc = this.dataPath ? this.dataPath : ''
        }
    },
    mounted() {
      this.dataSrc = this.dataPath ? this.dataPath : ''
    },
    methods: {
      viewPdf(){
          window.open(this.dataSrc)
      },
      upload() {
          uploadFile({
            accept: '.jpg,.png,.pdf,.doc'
          })
          .then(file => {
              if (!/(\.jpg|\.png|\.pdf|\.doc)$/.test(file.name.toLowerCase())) {
                  this.$message({
                      type: 'warning',
                      message: this.$t('global.typeWarn',{0: '.jpg|.png|.pdf|.doc'})
                  })
                  return false;
              }

              let formData = new FormData()
              formData.append('uploadFile', file)
              this.$post({
                  url: '/upload',
                  data: formData
              })
              .then(res => {
                  this.dataSrc = res.url
                  this.$emit('pathMethod', res.path)
              })
          })
      },
    }
  }
</script>

<style scoped lang="scss">
  .upload-part {
    .view-img {
      max-width: 90%;
      height: auto;
      max-height: 500px;
    }
    .tips-txt{
      font-size: 12px;
      color: #B2B2B2;
      line-height: 30px;
    }
  }
</style>
